<template>
  <div class="workbench">
    <div class="overview">
      <div class="navigate">
        <div class="navigate-box">
          <a class="smart-exam item" @click="goUrl('exam')">
            <img src="@/assets/images/workbench/smart-exam.svg?url" />
          </a>
          <a class="smart-homework item" @click="goUrl('homework')">
            <img src="@/assets/images/workbench/smart-homework.svg?url" />
          </a>
          <a
            class="smart-classroom item disabled"
            @click="goUrl('teachingSearch')"
          >
            <img src="@/assets/images/workbench/teaching-search.svg?url" />
          </a>
          <a class="item" @click="goUrl('smartRoom')">
            <img src="@/assets/images/workbench/smart-room.svg?url" />
          </a>
        </div>
      </div>
      <div class="count-items">
        <div class="title">作业开展统计</div>
        <div class="count-box">
          <StatisticsItem
            icon-class="icon"
            :icon-src="classroomCountIcon"
            label="应用班级数"
            count-color="#7ab189"
            :current-value="statistics?.now_week.class_count"
            :previous-value="statistics?.last_week.class_count"
          />
          <StatisticsItem
            icon-class="icon"
            :icon-src="teacherCountIcon"
            label="应用教师数"
            count-color="#88acf4"
            :current-value="statistics?.now_week.teacher_count"
            :previous-value="statistics?.last_week.teacher_count"
          />
          <StatisticsItem
            icon-class="icon"
            :icon-src="assignmentCountIcon"
            label="班周均布置次数"
            count-color="#5bc4d3"
            :current-value="statistics?.now_week.class_avg_count"
            :previous-value="statistics?.last_week.class_avg_count"
            unit="次/班"
          />
          <StatisticsItem
            icon-class="icon"
            :icon-src="submitRateIcon"
            label="提交率"
            count-color="#fbc25e"
            :current-value="statistics?.now_week.commit_rate * 100"
            :previous-value="statistics?.last_week.commit_rate * 100"
            unit="%"
          />
          <StatisticsItem
            icon-class="icon"
            :icon-src="alertPercentageIcon"
            label="待批改任务数"
            count-color="#c9b1fd"
            :current-value="statistics?.now_week.un_corrected_count"
            :previous-value="statistics?.last_week.un_corrected_count"
            unit="个"
          />
        </div>
      </div>

      <div class="trend">
        <div class="title">作业应用趋势</div>
        <!-- 图表 -->
        <TrendChart />
      </div>
    </div>
    <div class="right info">
      <ProfileCard :teachingInfo :classroomList :subjectList />
    </div>
  </div>
</template>
<script setup>
import { ref, onBeforeMount, watch } from 'vue'

import { ElMessage } from 'element-plus'
import { useAuthStore, ROLE_ENUM } from '@/stores'
import { getAdminList } from '@/apis'
import { getSmartRoomToken } from '@/apis/workbench/index.js'
import TrendChart from './components/TrendChart.vue'
import ProfileCard from './components/ProfileCard.vue'
import StatisticsItem from './components/StatisticsItem.vue'
import classroomCountIcon from '@/assets/images/workbench/classroom-count.svg?url'
import teacherCountIcon from '@/assets/images/workbench/teacher-count.svg?url'
import assignmentCountIcon from '@/assets/images/workbench/assignment-count.svg?url'
import submitRateIcon from '@/assets/images/workbench/submit-rate.svg?url'
import alertPercentageIcon from '@/assets/images/workbench/alert-percentage.svg?url'

import { postStatistics, postTeachingInfo, postExamSystemToken } from '@/apis'

const env = import.meta.env.VITE_ENV
console.log(env)

const authStore = useAuthStore()
const { userInfo } = authStore

const link = {
  prod: {
    exam: 'https://single-yue.readboy.com/#/Login',
    homework: 'https://zuoye.readboy.com',
    teachingSearch: 'https://ebag.readboy.com/teaching-learning-research',
    smartRoom: 'https://aizxs.readboy.com/app-ailearn'
  },
  test: {
    exam: 'https://ebag-test.readboy.com/examination-web/#/Login',
    homework: 'https://ebag-test.readboy.com/smart-homework',
    teachingSearch: 'https://ebag-test.readboy.com/teaching-learning-research',
    smartRoom: 'https://aizxs-test.readboy.com/app-ailearn'
  }
}

// 跳转到指定系统
const goUrl = async system => {
  if (system === 'teachingSearch') {
    ElMessage.warning('暂未开通')
    return
  }

  // 拿到指定环境的链接
  const baseLink = link[env][system]
  let commonParams
  const {
    userId,
    userName,
    sessionId,
    userType,
    platform,
    school_id,
    school_name,
    organ_type
  } = userInfo
  if (system === 'smartRoom') {
    const res = await getAdminData()
    if (!res) {
      ElMessage.error('您暂无爱学空间权限，请通知管理员提供权限')
      return
    }
    const { code, msg, data } = await getSmartRoomToken({
      teacher_id: +userId
    })
    if (code === 100400) {
      ElMessage.error('您暂无爱学空间权限，请通知管理员提供权限')
      return
    } else if (code !== 100200) {
      ElMessage.error(msg)
      return
    } else {
      commonParams = `token=${data}&platform=ai-study&ebag_school_id=${school_id}&ebag_school_name=${school_name}&ebag_token=${sessionId}&ebag_platform=${platform}&ebag_user_id=${userId}&ebag_user_type=${userType}&ebag_role_code=${authStore.nowGlobalRole.role_code}&organ_type=${organ_type}`
    }
  } else if (system !== 'exam') {
    commonParams = `token=${sessionId}&userId=${userId}&userName=${userName}&user_id=${userId}&user_name=${userName}&authType=ai&userType=${userType}&platform=${platform}&stage=${authStore.nowGlobalStageId}&subject_id=${authStore.nowGlobalSubjectId}`
  } else {
    const { token, user_name, user_id } = await postExamSystemToken({
      token: sessionId,
      user_id: userId
    })
    commonParams = `token=${token}&user_id=${user_id}&user_name=${user_name}`
  }

  console.log(`${baseLink}?${commonParams}`)

  window.open(`${baseLink}?${commonParams}`)
}

const getAdminData = async () => {
  const { data } = await getAdminList({
    schoolId: authStore.userInfo.school_id,
    roleCode: ROLE_ENUM.StoreManager
  })
  return (data?.list?.length || 0) > 0
}

// 获取教师信息
const teachingInfo = ref([])
const subjectList = ref([])

// 教的班级列表
const classroomList = ref([])

onBeforeMount(async () => {
  const params = {
    teacher_id: userInfo.userId
  }
  const res = await postTeachingInfo(params)

  teachingInfo.value = res.data
  console.log(teachingInfo.value)
  // 只保留一个同名的学科
  subjectList.value = teachingInfo.value
    ?.map(item => item.subject_list)
    .flat()
    .filter(
      (item, index, self) =>
        index === self.findIndex(t => t?.code === item?.code)
    )
  // 班级去重
  classroomList.value = [
    ...new Set(
      teachingInfo.value?.map(item => ({
        name: item.grade_name + item.class_name,
        id: item.id
      }))
    )
  ]
  userInfo.subjectList = subjectList.value
  userInfo.classroomList = classroomList.value
  if (authStore.nowIsSmartRoomCode) {
    authStore.getTeachingInfo(authStore.nowGlobalRole.role_code)
  }
})

const statistics = ref(null)
watch(
  () => authStore.globalSubjectList,
  async val => {
    if (val?.length === 0) return
    const params = {
      subject_id: val?.map(item => item.subject_num) || []
    }
    const res = await postStatistics(JSON.stringify(params))
    statistics.value = res?.data
  },
  { immediate: true }
)
</script>
<style lang="less" scoped>
.workbench {
  width: 100%;
  height: 95vh;
  display: flex;
  gap: 32px;

  .overview,
  .right {
    height: 100%;
  }

  .overview {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    gap: 25px;
    width: 1246px;

    .title {
      display: flex;
      align-items: center;
      font-size: 22px;
      height: 35px;
      margin-bottom: 20px;
      color: #040b1a;
      font-weight: 500;

      &::before {
        content: '';
        display: inline-block;
        width: 7px;
        height: 22px;
        background-color: #428fff;
        margin-right: 16px;
      }
    }

    .navigate {
      display: flex;
      flex-direction: column;
      height: 119px;

      .navigate-box {
        display: flex;
        justify-content: space-between;
        height: 100%;
        gap: 23px;

        .item {
          cursor: pointer;

          &.disabled {
            cursor: not-allowed;
          }
        }
      }
    }

    .count-items {
      display: flex;
      flex-direction: column;
      height: 185px;
      .count-box {
        display: flex;
        justify-content: space-between;
        gap: 18px;
      }
    }
    .trend {
      flex: 1;
      display: flex;
      flex-direction: column;
    }
  }

  .right {
    width: 354px;
  }
}
</style>
